package com.fer.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SIGN = "!@QERqwer323@#dsq#$%!%&";

    /**
     * 生成token  header.payload.sign
     * @param map   设置在payload的数据（key， value）
     * @return
     */
    public static String getToken(Map<String, String> map){

        // 设置默认7天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        // 创建jwt
        JWTCreator.Builder builder = JWT.create();

        map.forEach((key, value) -> {
            builder.withClaim(key, value);
        });

        String token = builder.withExpiresAt(calendar.getTime()) // 指定令牌过期时间为7天
                .sign(Algorithm.HMAC256(SIGN)); // 令牌密钥

        return token;
    }

    /**
     * 验证token合法性
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        DecodedJWT verify = build.verify(token);
        return verify;
    }

}
